import { login, crmLogin, logout } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import Cookies from 'js-cookie'

const APP_USER_INFO_KEY = '__APP_USER_INFO__'

const getLocalStorage = key => {
  const storage = JSON.parse(localStorage.getItem(APP_USER_INFO_KEY))
  return key ? (storage[key] ? storage[key] : '') : storage
}

const getDefaultState = () => {
  return {
    // 这些都是state的信息
    token: getToken(),
    userId: Cookies.get('userId'),
    role: Cookies.get('role'),
    userName: Cookies.get('userName'),
    realName: Cookies.get('realName'),
    userSource: Cookies.get('userSource'),
  }
}

const state = getDefaultState()
const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USER_ID: (state, userId) => {
    state.userId = userId
  },
  SET_ROLE: (state, role) => {
    state.role = role
  },
  SET_USER_NAME: (state, userName) => {
    state.userName = userName
  },
  SET_REAL_NAME: (state, realName) => {
    state.realName = realName
  },
  SET_USER_SOURCE: (state, userSource) => {
    state.userSource = userSource
  }

}
const actions = {
  // user login
  login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      login(userInfo).then(response => {
        console.log('response.data.role', response.data.role)
        console.log('response.data.role', typeof response.data.role)
        localStorage.setItem(APP_USER_INFO_KEY, JSON.stringify(response.data))
        // token
        Cookies.set('SET_TOKEN', response.data.accessToken)
        var token = response.data.accessToken
        commit('SET_TOKEN', token)
        setToken(token)
        // userId
        Cookies.set('userId', response.data.userId)
        commit('SET_USER_ID', response.data.userId)
        // role
        // debugger
        Cookies.set('role', response.data.role)
        commit('SET_ROLE', response.data.role)
        // userName
        Cookies.set('userName', response.data.username)
        commit('SET_USER_NAME', response.data.username)
        // realName
        Cookies.set('realName', response.data.realName)
        commit('SET_REAL_NAME', response.data.realName)
        // userSource
        Cookies.set('userSource', response.data.userSource)
        commit('SET_USER_SOURCE', response.data.userSource)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // crm user login
  crmLogin({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      crmLogin(userInfo).then(response => {
        localStorage.setItem(APP_USER_INFO_KEY, JSON.stringify(response.data))
        // token
        Cookies.set('SET_TOKEN', response.data.accessToken)
        var token = response.data.accessToken
        commit('SET_TOKEN', token)
        setToken(token)
        // userId
        Cookies.set('userId', response.data.userId)
        commit('SET_USER_ID', response.data.userId)
        // role
        // debugger
        Cookies.set('role', response.data.role)
        commit('SET_ROLE', response.data.role)
        // userName
        Cookies.set('userName', response.data.username)
        commit('SET_USER_NAME', response.data.username)
        // realName
        Cookies.set('realName', response.data.realName)
        commit('SET_REAL_NAME', response.data.realName)
        // userSource
        Cookies.set('userSource', response.data.userSource)
        commit('SET_USER_SOURCE', response.data.userSource)
        resolve()
      }).catch(error => {
        console.log('userInfo', userInfo)
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout().then(() => {
        localStorage.removeItem(APP_USER_INFO_KEY)
        removeToken() // must remove  token  first
        Cookies.remove('SET_TOKEN')
        Cookies.remove('userId')
        Cookies.remove('role')
        Cookies.remove('userName')
        Cookies.remove('realName')
        Cookies.remove('userSource')


        window.location.reload() // f5
        resetRouter()
        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })
        // resolve() //
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    // return new Promise((resolve, reject) => {
    //   getInfo(state.token).then(response => {
    //     const { data } = response

    //     if (!data) {
    //       return reject('Verification failed, please Login again.')
    //     }

    //     const { userName } = data

    //     commit('SET_USER_NAME', userName)
    //     // commit('SET_AVATAR')
    //     resolve(data)
    //   }).catch(error => {
    //     reject(error)
    //   })
    // })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve, reject) => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  },
  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true, // 必须写
  state,
  mutations,
  actions
}

